import 'dart:math';

import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';
import 'package:flutter_sample/test.dart';

import '../util/app_colors.dart';
import '../util/app_utils.dart';

class BarChartSample5 extends StatefulWidget {
  const BarChartSample5({super.key});

  @override
  State<StatefulWidget> createState() => BarChartSample5State();
}

class BarChartSample5State extends State<BarChartSample5> {
  static const double barWidth = 2;
  static const shadowOpacity = 0.2;
  static const mainItems = <int, List<double>>{
    0: [0.5, 0.2, 0.3, 0.4],
    1: [-0.3, -0.2, -0.3, -0.4],
    2: [0.3, 0.2, 0.3, 0.4],
    3: [-0.2, -0.2, -0.3, -0.4],
    4: [0.8, 0.2, 0.3, 0.4],
    5: [-0.9, -0.2, -0.3, -0.4],
    6: [0.7, 0.2, 0.3, 0.4],
    7: [-0.4, -0.2, -0.3, -0.4],
    8: [0.5, 0.2, 0.3, 0.4],
  };
  int touchedIndex = -1;

  var mainList = List.generate(
    (48),
    (index) => index % 2 ==0 ? 0.5 : -0.5,

  );

  @override
  void initState() {
    super.initState();
  }

  Widget bottomTitles(double value, TitleMeta meta) {
    print("michaelliu value $value");
    const style = TextStyle(color: Colors.white, fontSize: 10);
    String text;
    switch (value.toInt()) {
      case 0:
        text = '0';
        break;
      case 12:
        text = '8';
        break;
      case 24:
        text = '16';
        break;
      case 36:
        text = '24';
        break;
      default:
        text = '';
        break;
    }
    return SideTitleWidget(meta: meta, child: Text(text, style: style));
  }

  Widget topTitles(double value, TitleMeta meta) {
    const style = TextStyle(color: Colors.white, fontSize: 10);
    String text;
    switch (value.toInt()) {
      case 0:
        text = '0';
        break;
      case 1:
        text = 'Tue';
        break;
      case 2:
        text = 'Wed';
        break;
      case 3:
        text = 'Thu';
        break;
      case 4:
        text = 'Fri';
        break;
      case 5:
        text = 'Sat';
        break;
      case 6:
        text = 'Sun';
        break;
      default:
        return Container();
    }
    return SideTitleWidget(meta: meta, child: Text(text, style: style));
  }

  Widget leftTitles(double value, TitleMeta meta) {
    const style = TextStyle(color: Colors.white, fontSize: 10);
    String text;
    if (value == 0) {
      text = '0';
    } else {
      text = '${value.toInt()}0k';
    }
    return SideTitleWidget(
      angle: AppUtils().degreeToRadian(value < 0 ? -45 : 45),
      meta: meta,
      space: 4,
      child: Text(text, style: style, textAlign: TextAlign.center),
    );
  }

  Widget rightTitles(double value, TitleMeta meta) {
    const style = TextStyle(color: Colors.white, fontSize: 10);
    String text = "";
    if (value == 0) {
      text = ' 0.0';
    } else if (value == 1) {
      text = ' +${value.toInt()}';
    } else if (value == -1) {
      text = ' ${value.toInt()}';
    }
    return SideTitleWidget(
      angle: AppUtils().degreeToRadian(0),
      meta: meta,
      space: 0,
      child: Text(text, style: style, textAlign: TextAlign.center),
    );
  }

  BarChartGroupData generateGroup(int x, double value1) {
    final isTop = value1 > 0;
    final sum = value1;
    final isTouched = touchedIndex == x;
    return BarChartGroupData(
      x: x,
      groupVertically: true,
      showingTooltipIndicators: isTouched ? [0] : [],
      barRods: [
        BarChartRodData(
          toY: sum,
          width: barWidth,
          borderRadius:
              isTop
                  ? const BorderRadius.only(
                    topLeft: Radius.circular(6),
                    topRight: Radius.circular(6),
                  )
                  : const BorderRadius.only(
                    bottomLeft: Radius.circular(6),
                    bottomRight: Radius.circular(6),
                  ),
          rodStackItems: [
            BarChartRodStackItem(
              0,
              value1,
              Colors.green,
              borderSide: BorderSide(color: Colors.green, width: isTouched ? 2 : 0),
            ),
          ],
        ),
      ],
    );
  }

  bool isShadowBar(int rodIndex) => rodIndex == 1;

  @override
  Widget build(BuildContext context) {
    var groups = <BarChartGroupData>[];

    for (int i = 0; i < mainList.length; i++) {
      double value = mainList[i];
      groups.add(generateGroup(i, value));
    }

    return Container(
      width: double.infinity,
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 16),
        child: Container(
          width: double.infinity,
          height: 180,
          child: BarChart(
            BarChartData(
              alignment: BarChartAlignment.start,
              maxY: 1,
              minY: -1,
              baselineY: 0,
              groupsSpace: 48,
              barTouchData: BarTouchData(
                touchTooltipData: BarTouchTooltipData(
                  tooltipBorderRadius: BorderRadius.circular(16),
                  fitInsideHorizontally: true,
                  direction: TooltipDirection.top,
                  getTooltipColor: (BarChartGroupData group) {
                    return Colors.white;
                  },
                  getTooltipItem: (
                    BarChartGroupData group,
                    int groupIndex,
                    BarChartRodData rod,
                    int rodIndex,
                  ) {
                    var children = <TextSpan>[
                        TextSpan(text: "\n2025-06-26")
                    ];

                    return BarTooltipItem("", textAlign: TextAlign.start, TextStyle(color: Colors.red),children: children);
                  },
                ),
                handleBuiltInTouches: false,
                touchCallback: (FlTouchEvent event, barTouchResponse) {
                  if (!event.isInterestedForInteractions ||
                      barTouchResponse == null ||
                      barTouchResponse.spot == null) {
                    setState(() {
                      touchedIndex = -1;
                    });
                    return;
                  }
                  final rodIndex = barTouchResponse.spot!.touchedRodDataIndex;
                  if (isShadowBar(rodIndex)) {
                    setState(() {
                      touchedIndex = -1;
                    });
                    return;
                  }
                  setState(() {
                    touchedIndex = barTouchResponse.spot!.touchedBarGroupIndex;
                  });
                },
              ),
              titlesData: FlTitlesData(
                show: true,
                topTitles: AxisTitles(
                  sideTitles: SideTitles(
                    showTitles: false,
                    reservedSize: 32,
                    getTitlesWidget: topTitles,
                  ),
                ),
                bottomTitles: AxisTitles(
                  sideTitles: SideTitles(
                    showTitles: true,
                    reservedSize: 32,
                    interval: 0.1,
                    getTitlesWidget: bottomTitles,
                  ),
                ),
                leftTitles: AxisTitles(
                  sideTitles: SideTitles(
                    showTitles: false,
                    getTitlesWidget: leftTitles,
                    interval: 5,
                    reservedSize: 42,
                  ),
                ),
                rightTitles: AxisTitles(
                  sideTitles: SideTitles(
                    showTitles: true,
                    getTitlesWidget: rightTitles,
                    interval: 1,
                    reservedSize: 42,
                  ),
                ),
              ),
              gridData: FlGridData(
                show: true,
                checkToShowHorizontalLine: (value) => (value == 0),
                getDrawingHorizontalLine: (value) {
                  if (value == 0) {
                    return FlLine(
                      color: AppColors.borderColor.withValues(alpha: 0.1),
                      strokeWidth: 1,
                    );
                  }
                  return FlLine(
                    color: AppColors.borderColor.withValues(alpha: 1),
                    strokeWidth: 0.8,
                  );
                },
              ),
              borderData: FlBorderData(
                show: true,
                border: Border(
                  top: BorderSide(color: Colors.green),
                  bottom: BorderSide(color: Colors.white),
                  left: BorderSide(color: Colors.white),
                  right: BorderSide(color: Colors.white),
                ),
              ),
              barGroups: groups,
            ),
          ),
        ),
      ),
    );
  }
}
